#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    //this->setWindowOpacity(1);
    l = new Login_Dialog(this);
    l->show();
    connect(l,SIGNAL(loginSuccess_Signal(QString,QString)),this,SLOT(login_Success_Slot(QString,QString)));
    connect(ui->lineEdit_search,SIGNAL(textEdited(QString)),this,SLOT(search_immediately()));
}

Dialog::~Dialog()
{
    if(db.isOpen())
    {
        db.close();
    }
    delete ui;
    delete dl;
    delete md;
    delete ad;
    delete s;
}

void Dialog::paintEvent(QPaintEvent *)
{
    int w = width();
    int h = height();
    QPainter painter(this);
    QPixmap map(skin_path);
    painter.drawPixmap(0,0,w,h,map);
}

bool Dialog::isExist(QString w)
{
       QString sql = "SELECT * FROM englishwords WHERE word=?";
       QSqlQuery sq;
       sq.prepare(sql);
       sq.addBindValue(w);
       if(sq.exec()) // 查询操作成功
       {
           if(sq.next()) // 存在
               return true;
       }else
       {
           QString text = sq.lastError().text();
           qDebug() << text;
       }
       return false;
}

void Dialog::on_pushButton_exit_clicked()
{
    close();
}

void Dialog::on_pushButton_about_clicked()
{
    QMessageBox::information(this,"软件信息","软件版本v1.0\n\
修改词条/删除词条需要在搜索栏进行输入\n\
删除词条支持模糊搜索删除第n条\n\
Designed by 王鸿君\n\
   2022.2.20");
}

void Dialog::login_Success_Slot(QString n, QString p)
{
    name = n;
    pass = p;
    this->show();
    connect2DB();
}

void Dialog::on_pushButton_quitlog_clicked()
{
    this->close();
    l->connect2DB();
    l->show();
}

void Dialog::on_pushButton_info_clicked()
{
    QString text = "用户名：";
    text.append(name).append("\n").append("密码:   ").append(pass);
    QMessageBox::information(this,"用户信息",text);
}

void Dialog::on_pushButton_fonts_clicked()
{
    QFont TextFont;
    QFont pushbuttonfont_font = ui->pushButton_fonts->font();//获取font
    QFont pushbuttonfont_about = ui->pushButton_about->font();//获取font
    QFont pushbuttonfont_exit = ui->pushButton_exit->font();//获取font
    QFont pushbuttonfont_history = ui->pushButton_history->font();//获取font
    QFont pushbuttonfont_info = ui->pushButton_info->font();//获取font
    QFont pushbuttonfont_search = ui->pushButton_search->font();//获取font
    QFont pushbuttonfont_quitlog = ui->pushButton_quitlog->font();//获取font

    bool ok = false;
    QFont Font = QFontDialog::getFont(&ok,TextFont);//选择字体，getFont无返回量，以变量ok作为是否选择成功标志
    if(ok)
    {
        ui->pushButton_fonts->setFont(Font);
        ui->pushButton_about->setFont(Font);
        ui->pushButton_exit->setFont(Font);
        ui->pushButton_history->setFont(Font);
        ui->pushButton_info->setFont(Font);
        ui->pushButton_search->setFont(Font);
        ui->pushButton_quitlog->setFont(Font);
        ui->pushButton_background->setFont(Font);
        ui->textBrowser->setFont(Font);
        ui->lineEdit_search->setFont(Font);
        ui->pushButton_modify->setFont(Font);
        ui->pushButton_delete->setFont(Font);
        ui->pushButton_add->setFont(Font);
    }
}

bool Dialog::connect2DB()
{
        // 通过不同数据库的驱动程序连接不同的数据库
        db = QSqlDatabase::addDatabase("QSQLITE");

        // 设置SQLite数据库文件的名称，此文件在构建目录中创建
        db.setDatabaseName("englishwords.db");

        // 设置连接的用户名的密码
        db.setUserName("admin");
        db.setPassword("admin");

        // 打开数据库连接
        if(db.open())
        {
            createDictabal();
            qDebug() << "单词库连接成功";
            return true;
        }else
        {
            QSqlError error = db.lastError();

            // 获得错误信息
            QString text = error.text();

            // 展示错误信息
            QMessageBox::critical(this,"错误",text);
            return false;
        }
}

/***********************历史记录建表***************************/
void Dialog::createDictabal()
{
    // 标准SQL建表语句
        QString sql = "CREATE TABLE history(words text)";
        // 创建数据库操作类对象
        QSqlQuery sq;
        // 执行上面的sql语句：正常情况下只有第一次建表成功
        if(sq.exec(sql))
        {
            qDebug() << "建history表成功！";
        }else
        {
            // 错误信息
            QString text = sq.lastError().text();
            qDebug() << "history" << text;
        }
}

/************************搜索按钮***********************************/
void Dialog::on_pushButton_search_clicked()
{
    ui->textBrowser->clear();
    //获取用户输入的单词
    QString user_words = ui->lineEdit_search->text();\
    //获取当前时间
    QString format = "yyyy-MM-dd hh:mm:ss";
    QString time_history = user_words;
    time_history.append("   ").append(QDateTime::currentDateTime().toString(format));

    //将用户的输入添加进历史记录表中
    QString sql = "INSERT INTO history VALUES(?)";
    QSqlQuery sq;
    sq.prepare(sql);
    sq.addBindValue(time_history);
    if(sq.exec())
    {
        qDebug() << "历史记录添加成功！" << endl;
    }else
    {
        // 错误信息
        QString text = sq.lastError().text();
        qDebug() << "插入失败" << text;
    }
    if(!isExist(user_words))
    {
        ui->textBrowser->append("未查询到结果");
        return;
    }
    //查询用户输入的单词
    QString sql2 = "SELECT * FROM englishwords WHERE word=?";
    QSqlQuery sq2;
    sq2.prepare(sql2);
    sq2.addBindValue(user_words);
    //精确搜索
    if(sq2.exec())
    {
        int count = 0;
        while(sq2.next())
        {
              count++;

              QString word_search = sq2.value(0).toString();
              QString pronunciation_search = sq2.value("pronunciation").toString();
              QString meaning_search = sq2.value("meaning").toString();
              word_search.append("--").append(pronunciation_search).append("--").append(meaning_search)\
                      .prepend(": ").prepend(QString::number(count)).prepend("单词");
              ui->textBrowser->append(word_search);
        }
        QString result = "共查询到";
        ui->label_2->setText(result.append(QString::number(count)).append("个结果"));
    }else
    {
        QString text2 = sq2.lastError().text();
        QMessageBox::critical(this,"错误",text2);
    }
}
/**********************查询历史*****************************************/
void Dialog::on_pushButton_history_clicked()
{
       ui->textBrowser->clear();
       QString sql = "SELECT * FROM history";
       QSqlQuery sq;
       if(sq.exec(sql))
       {
           // 循环取出所有的结果，类似于java迭代器
           while(sq.next()) // 每次循环是一行数据（一条记录）
           {
               //可以使用列序号（也可以列名）获得具体列的数据
               QString word_history = sq.value(0).toString();
               //显示
               ui->textBrowser->append(word_history);
           }
       }else
       {
           // 错误信息
           QString text = sq.lastError().text();
           QMessageBox::critical(this,"错误",text);
       }
}

/************************************模糊查询*************************************/
void Dialog::search_immediately()
{
    ui->textBrowser->clear();
    int count = 0;
    QString user_words = ui->lineEdit_search->text();
    //查询用户输入的单词
        QString sql = "SELECT * FROM englishwords WHERE word LIKE ?";
        QSqlQuery sq;
        sq.prepare(sql);
        sq.addBindValue(user_words.append("%"));
        if(sq.exec())
        {
            while(sq.next())
            {
                count++;
                QString word_search = sq.value(0).toString();
                QString pronunciation_search = sq.value("pronunciation").toString();
                QString meaning_search = sq.value("meaning").toString();
                word_search.append("--").append(pronunciation_search).append("--").append(meaning_search)\
                        .prepend(": ").prepend(QString::number(count)).prepend("单词");
                ui->textBrowser->append(word_search);
                if(count > 20)
                {
                    break;
                }
            }
            QString number = "共查询到"+QString::number(sq.size())+"个结果";
            ui->label_2->setText(QString::number(count).append("个结果").prepend("共查询到"));
        }else
        {
            QString text = sq.lastError().text();
            QMessageBox::critical(this,"错误",text);
        }

}
/************************************切换主题************************************/
void Dialog::on_pushButton_background_clicked()
{
    //创建皮肤窗口
    s = new skin(this);
    connect(s,SIGNAL(skinemit_signal(int)),this,SLOT(skin_slot(int)));
    s->show();
}

void Dialog::skin_slot(int num)
{
    QString skin1 = ":/new/back/backimp/summer.png";
    QString skin2 = ":/new/back/backimp/绯红.png";
    QString skin3 = ":/new/back/backimp/灵魂莲华.png";
    QString skin4 = ":/new/back/backimp/夜晚.png";
    switch(num)
    {
        case 1:
        {
            skin_path = skin1;
            close();
            this->show();
            break;
        }
        case 2:
        skin_path = skin2;
        close();
        this->show();
            break;
        case 3:
        skin_path = skin3;
        close();
        this->show();
            break;
        case 4:
        skin_path = skin4;
        close();
        this->show();
            break;
        default:
            break;

    }
}

/******************************************删除词条*****************************************/
void Dialog::on_pushButton_delete_clicked()
{
    QString user_words = ui->lineEdit_search->text();
    if(user_words == "")
    {
        QMessageBox::information(this,"通知","请输入你要删除的单词");
        return;
    }

    //查询用户输入的单词
    QString sql2 = "SELECT * FROM englishwords WHERE word LIKE ?";
    QSqlQuery sq2;
    int count = 0;
    sq2.prepare(sql2);
    QString words_sq = user_words;
    words_sq.append("%");
    sq2.addBindValue(words_sq);
    //模糊搜索
    if(sq2.exec())
    {
        while(sq2.next())
        {
              count++;
        }
    }else
    {
        QString text2 = sq2.lastError().text();
        QMessageBox::critical(this,"错误",text2);
    }
    qDebug() <<"查询单词数量" << count;
    //如果结果大于1则弹出窗口让用户选择
    if(count > 1)
    {
        sq2.first();
        dl = new Dlete_select(this);
        connect(dl,SIGNAL(return_deletenum_signal(int)),this,SLOT(get_Deletenum_Slot(int)));
        dl->show();
    }else if(count == 1)//否则就直接删除
    {
        QString sql3 = "DELETE FROM englishwords WHERE word=?";
        QSqlQuery sq3;
        qDebug()<<"************"<<user_words;
        sq3.prepare(sql3);
        sq3.addBindValue(user_words);
        if(sq3.exec())
        {
            QMessageBox::information(this,"删除","删除成功!");
            qDebug() << "删除" << user_words << "成功";
        }else
        {
            QString text4 = sq3.lastError().text();
            QMessageBox::critical(this,"错误",text4);
        }
    }else
    {
        QMessageBox::warning(this,"警告","未查询到该单词");
        return;
    }
}
/***********************************删除词条槽函数*****************************/
void Dialog::get_Deletenum_Slot(int num)
{
    qDebug() << "信号槽返回" << num;
    QString user_words = ui->lineEdit_search->text();
    //查询用户输入的单词
    QString sql2 = "SELECT * FROM englishwords WHERE word LIKE?";
    QSqlQuery sq2;
    int i = 0;
    sq2.prepare(sql2);
    sq2.addBindValue(user_words.append("%"));
    //精确搜索
    if(sq2.exec())
    {
        for(i = 0;i<num;i++)
        {
            sq2.next();
        }
        QString sql3 = "DELETE FROM englishwords WHERE word=?";
        QSqlQuery sq3;
        sq3.prepare(sql3);
        sq3.addBindValue(sq2.value(0).toString());
        if(sq3.exec())
        {
            if(sq2.value(0).toString() != "")
            {
                QMessageBox::information(this,"删除","删除成功!");
                qDebug() << "删除" << sq2.value(0).toString() << "成功";
            }else
            {
                QMessageBox::warning(this,"警告","删除失败，请联系管理员反应问题!");
                return;
            }
        }else
        {
            QString text4 = sq3.lastError().text();
            QMessageBox::critical(this,"错误",text4);
        }

    }else
    {
        QString text2 = sq2.lastError().text();
        QMessageBox::critical(this,"错误",text2);
    }
}

void Dialog::on_pushButton_add_clicked()
{
    ad = new Add_dialog(this);
    connect(ad,SIGNAL(sendAddInput(QString,QString,QString)),this,SLOT(get_Addinput_Slot(QString,QString,QString)));
    ad->show();
}

//从add_dialog中获得用户想要添加的词条信息槽函数
void Dialog::get_Addinput_Slot(QString words, QString pronunciation, QString meaning)
{
    if(words == "")
    {
        QMessageBox::information(this,"通知","请输入你要添加的单词");
        return;
    }
    QString sql = "INSERT INTO englishwords VALUES(?,?,?)";
    QSqlQuery sq;
    sq.prepare(sql);
    sq.addBindValue(words);
    sq.addBindValue(pronunciation);
    sq.addBindValue(meaning);

    if(sq.exec())
    {
        QMessageBox::information(this,"通知","添加词条成功");
        return;
    }else
    {
        QMessageBox::warning(this,"通知","添加失败");
        qDebug() << "添加词条错误";
        return;
    }
}

void Dialog::on_pushButton_modify_clicked()
{
    if(ui->lineEdit_search->text() == "")
    {
        QMessageBox::warning(this,"通知","请在搜索栏输入你要修改的单词");
    }
    md = new Modify_Dialog(this);
    if(!isExist(ui->lineEdit_search->text()))
     {
        QMessageBox::warning(this,"警告","没有找到该单词");
        return;
    }
    md->get_word(ui->lineEdit_search->text());
    connect(md,SIGNAL(sendModify_Slot(QString,QString,QString)),this,SLOT(get_Modifyinput_Slot(QString,QString,QString)));
    md->show();
}

void Dialog::get_Modifyinput_Slot(QString word, QString pronunciation, QString meaning)
{
    QString sql = "UPDATE englishwords SET pronunciation=?,meaning=? WHERE word=?";
    QSqlQuery sq;
    sq.prepare(sql);
    sq.addBindValue(pronunciation);
    sq.addBindValue(meaning);
    sq.addBindValue(word);
    // 执行SQL语句
    if(sq.exec())
    {
        QMessageBox::information(this,"通知","修改成功！");
    }else
    {
        // 错误信息
        QString text = sq.lastError().text();
        qDebug() << "修改失败" << text;
    }
}
